var datas=[];

layui.use(['treetable','element'], function() {

    var element = layui.element;
    var treetables = layui.treetable;
    var layer = layui.layer;
    var table = layui.table;
    var $ = layui.jquery;
    var re;
    queryall();
    // 渲染表格
    window.renderTable = function () {
        layer.load(5);
        re = treetables.render({
            elem: '#Lay_category_treeTable',
            data: datas,
            treeColIndex: 2,          // 树形图标显示在第几列
            treeSpid: 0,             // 最上级的父级id
            treeIdName: 'code',       // 	id字段的名称
            treePidName: 'pid',    // 	pid字段的名称
            treeDefaultClose: true,     //是否默认折叠
            page: false,
            //treeLinkage: true,      //父级展开时是否自动展开所有子级
            cols: [[
                {title: "公司部门列表", field: "name", align: "left"},
                {title: "操作", templet: "#updateAndDelete",width:248}
            ]],
            done: function () {
                layer.closeAll('loading');
            }
        })
        re.expandAll('#Lay_category_treeTable');
    };
    renderTable();
    element.render();
    //展开所有
    $('#btn-expand').click(function () {
        //alert(0)
        re.expandAll('#Lay_category_treeTable');
    });
    //折叠所有
    $('#btn-fold').click(function () {
        // alert(1)
        re.foldAll('#Lay_category_treeTable');
    });
    //新增公司
    $('#btn-intab').click(function () {
        parent.intab("views/jsp/SystemCenter/tpl/newupcompany.jsp","新增公司");
    });

})

//执行编辑修改
function toOpenUpdateLayer(id,pid,code) {
    if(code=='0'){
        parent.intab("views/jsp/SystemCenter/tpl/newupdepartment.jsp?id="+id,"修改部门");
    }else{
        if(pid=='0') parent.intab("views/jsp/SystemCenter/tpl/newupcompany.jsp?id="+id,"修改公司")
        else parent.intab("views/jsp/SystemCenter/tpl/newupdepartment.jsp?id="+id,"修改部门");
    }
}

//执行添加
function  toOpenNewLayer(pid,code,d) {
    if(code=="0"){//添加公司
        parent.intab("views/jsp/SystemCenter/tpl/newupcompany.jsp","新增公司");
    }else{//添加部门
        parent.intab("views/jsp/SystemCenter/tpl/newupdepartment.jsp?pid="+code,"新增部门");
    }

}

//执行删除
function doDelete(id,name,listlength) {
    //确认；如果点击确认删除；否则不删除
    layui.use(['layer'], function () {
        var layer = layui.layer;
        if(listlength>0)
            layer.alert(name+"下有部门，不能执行删除操作")
        else
            layer.confirm('确定要删除'+name+'吗？', {icon: 3, title: '确认删除'}, function (index) {
                deleteByid(id);
                /*$.ajax({
                    url: "",
                    data: "aid=" + classId,
                    success: function (data) {
                        layer.alert("删除" + data.msg, {time: 2000});
                        // table.reload("Lay_back_table");
                        layer.close(index);
                    }
                })*/
                //layer.alert("删除成功");
                //刷新表格树
                //renderTable();
            });
    });
}
function deleteByid(id) {
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        data:{"id":id},
        url:'department/deleteByKey',
        dataType:"json",
        /*  contentType: 'application/json',*/
        async:false,
        success : function (da) {
            if(da.status==200 ){
                var num=da.data;
                if(num <10000 && num >0){
                    layer.alert("删除成功");
                    datas=[];
                    queryall();
                    renderTable();
                }else if(num <10000 && num==0){
                    layer.alert("本地删除失败!");
                }else if (num >10000){
                    layer.alert("同步云枢删除失败!");
                    datas=[];
                    queryall();
                    renderTable();
                }

            }
        },
        error: function(data) {
            layer.msg("删除失败!");
        }
    });
}
//获取组织机构树
function queryall() {
    $.ajax({
        type : 'POST',
        //  url : 'resource/getTree',
        url:'department/selectTree',
        dataType:"json",
        contentType: 'application/json',
        async:false,
        success : function (da) {
            if(da.status==200 ){
                // datas=da.data
               // datas=da.data;
               // datas[0]=da.data;
                var data=da.data;
               var obj={};
                obj.id=data.id;
                obj.code=data.code;
                obj.name=data.name;
                obj.desc=data.desc;
                obj.createTime=data.createTime;
                obj.creator=data.creatorl;
                obj.pid=data.pid;
                obj.companyCode=data.companyCode;
                obj.users=data.users;
                obj.list=initData(data.list);
                obj.children=obj.list;
               datas.push(obj);
               // datas= initData(data.list);
            }
        },
        error: function(data) {
            layer.msg("初始化失败!");
        }
    });
}
function initData(data) {
    var object=[];
     for(var i=0;i<data.length;i++){
         var obj={};
            obj.id=data[i].id;
            obj.code=data[i].code;
            obj.name=data[i].name;
            obj.desc=data[i].desc;
            obj.createTime=data[i].createTime;
            obj.creator=data[i].creator;
            obj.companyCode=data[i].companyCode;
            obj.users=data[i].users;
            obj.pid=data[i].pid;
             if(data[i].list != null){
                 obj.list=initData(data[i].list);
             }
            obj.children=obj.list;
             object.push(obj);
     }

    return object;
}
/*
"id":3,"code":"0","name":"集团公司2",
    "desc":null,"createTime":null,"creator":null,"pid":1,
    "companyCode":null,"children":*/
